package helper;

import java.sql.*;

/**
 * @author Pascal de Vink
 * @version 0.2
 */
public class MysqlDatabase {

	static private Statement stmt;
	private String server;
	private String database;
	private String username;
	private String password;
	
	public MysqlDatabase(String server, String database, String username, String password)
	{
		this.server = server;
		this.database = database;
		this.username = username;
		this.password = password;
		openDatabase();
	}
	
	private void openDatabase()
	{
		if (MysqlDatabase.stmt == null) {
			try {	
			    //Register the JDBC driver for MySQL.
			    Class.forName("com.mysql.jdbc.Driver");
	
			    //Define URL of database server for
			    // database named mysql on the localhost
			    // with the default port number 3306.
			    String url = "jdbc:mysql://"+this.server+":3306/"+this.database;
			    System.out.println("URL: " + url);
			    System.out.println("username: " + this.username);
			    System.out.println("password: " + this.password);
			    
			    //Get a connection to the database for a
			    // user named root with a blank password.
			    // This user is the default administrator
			    // having full privileges to do anything.
			    Connection con = DriverManager.getConnection(url,this.username, this.password);
	
			    //Display connection information
			    System.out.println("Connection: " + con);
	
			    //Get a Statement object
			    MysqlDatabase.stmt = con.createStatement();
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("Database error while opening.");
				System.exit(1);
			}
		}
	}
	
	public void execute(String sql)
	{
		try {
			MysqlDatabase.stmt.execute(sql);
		} catch (SQLException e) {
			System.out.println("Database error while executing statements.");
			System.exit(1);
		}
	}
	
	public void closeDatabase()
	{
		if (MysqlDatabase.stmt != null)
		{
			try {
				MysqlDatabase.stmt.close();
			} catch (SQLException e) {
				System.out.println("Database error while closing.");
				System.exit(1);
			}
		}
	}
}
